//
//  RssFeedViewController.m
//  Lettore RSS Feed
//
//  Created by Dario Trisciuoglio on 09/06/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "RssFeedViewController.h"
#import "ViewArticolo.h"

@implementation RssFeedViewController


- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.title = @"EuroTrip.it RSS";
	//self.title = @"back";
	
	NSString *path = @"http://feeds.feedburner.com/eurotripit";
	[self parseXMLFileAtURL:path];
	// Grazie a queste due prime istruzioni creiamo un pulsante per aggiornare i nostri Rssfeed
	UIBarButtonItem *tastoAggiorna = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:self action:@selector(aggiornaFeed)];
	self.navigationItem.rightBarButtonItem = tastoAggiorna;
	
}

- (void)aggiornaFeed{
	// Grazie a queste due prime istruzioni facciamo un nuovo parsing XML e scarichiamo nuovamente i nostri feed RSS aggiornati al momento stesso della pressione del tasto
	NSString *path = @"http://feeds.feedburner.com/eurotripit";
	[self parseXMLFileAtURL:path];
	// Con questa, invece, ricarichiamo i nuovi dati nella tabella, sostituendo il nuovo elenco news al vecchio.
	[self.tableView reloadData];
}

- (void)parseXMLFileAtURL:(NSString *)URL {
	// inizializziamo la lista degli elementi
	elencoFeed = [[NSMutableArray alloc] init];
	
	// dobbiamo convertire la stringa "URL" in un elemento "NSURL"
	NSURL *xmlURL = [NSURL URLWithString:URL];
	
	// inizializziamo il nostro parser XML
	rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
	
	[rssParser setDelegate:self];
	
	// settiamo alcune proprietà
	[rssParser setShouldProcessNamespaces:NO];
	[rssParser setShouldReportNamespacePrefixes:NO];
	[rssParser setShouldResolveExternalEntities:NO];
	
	// avviamo il parsing del feed RSS
	[rssParser parse];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{			
    
	currentElement = [elementName copy];
	if ([elementName isEqualToString:@"item"]) {
		// inizializza tutti gli elementi
		item = [[NSMutableDictionary alloc] init];
		currentTitle = [[NSMutableString alloc] init];
		currentDate = [[NSMutableString alloc] init];
		currentSummary = [[NSMutableString alloc] init];
		currentLink = [[NSMutableString alloc] init];
	}
}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{     
	
	if ([elementName isEqualToString:@"item"]) {
		/* salva tutte le proprietà del feed letto nell'elemento "item", per
		 poi inserirlo nell'array "elencoFeed" */
		[item setObject:currentTitle forKey:@"title"];
		[item setObject:currentLink forKey:@"link"];
		[item setObject:currentSummary forKey:@"summary"];
		[item setObject:currentDate forKey:@"date"];
		
		[elencoFeed addObject:[item copy]];
	}
}



- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{;
	// salva i caratteri per l'elemento corrente
	if ([currentElement isEqualToString:@"title"]){
		[currentTitle appendString:string];
	} else if ([currentElement isEqualToString:@"link"]) {
		[currentLink appendString:string];
	} else if ([currentElement isEqualToString:@"description"]) {
		[currentSummary appendString:string];
	} else if ([currentElement isEqualToString:@"pubDate"]) {
		[currentDate appendString:string];
	}
}

- (void) parserDidEndDocument:(NSXMLParser *)parser {
	[self.tableView reloadData];
}


- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release anything that can be recreated in viewDidLoad or on demand.
	// e.g. self.myOutlet = nil;
}


#pragma mark Table view methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [elencoFeed count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
	
	// Configure the cell.
	cell.textLabel.text = [[elencoFeed objectAtIndex:indexPath.row] objectForKey:@"title"];
	
	return cell;
}

// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	// ricaviamo il link dell'elemento selezionato
	NSString *link = [[elencoFeed objectAtIndex:indexPath.row] objectForKey: @"link"];
	
	// ripiliamo il link da spazi, return e tabs
	link = [link stringByReplacingOccurrencesOfString:@" " withString:@""];
	link = [link stringByReplacingOccurrencesOfString:@"\n" withString:@""];
	link = [link stringByReplacingOccurrencesOfString:@"	" withString:@""];
	
	// apriamo la nuova vista
	ViewArticolo *controller = [[ViewArticolo alloc] initWithNibName:@"ViewArticolo" bundle:nil];
	controller.indirizzo = link;
	[self.navigationController pushViewController:controller animated:YES];
}


- (void)dealloc {
	[currentElement release];
	[rssParser release];
	[elencoFeed release];
	[item release];
	[currentTitle release];
	[currentDate release];
	[currentSummary release];
	[currentLink release];
	
    [super dealloc];
}


@end